package com.xk.blog.controller.admin;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.xk.blog.common.JsonResult;
import com.xk.blog.controller.BaseController;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/admin/uploadfile")
public class UploadPhotoController extends BaseController {

    /**
     * 上传压缩文件，只能是zip或rar
     * 
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/photo")
    @ResponseBody
    public JsonResult uploadZip(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String path = request.getSession().getServletContext().getRealPath("static/upload");
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.indexOf("."));
        fileName = System.currentTimeMillis() + fileName;
        if (file != null && file.getSize() > 0) {
            File targetFile = new File(path, fileName);
            try {
                if (!targetFile.exists()) { // 判断文件的路径是否存在
                    targetFile.createNewFile();
                }
                file.transferTo(targetFile); // 传送 失败就抛异常
                Thread.sleep(3000);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        System.out.println(fileName);// 后台输出你要存放文件的路径名 方便查错
        return JsonResult.ok(fileName);
    }

}
